using System;
using Game.Scripts.ScriptableObject;
using UnityEngine;
using UnityEngine.Pool;

namespace Game.Scripts.Service
{
    public class ObjectPoolService : MonoBehaviour
    {
        public IObjectPool<GameObject> heartObjectPool { get; private set; }
        [SerializeField] private ObjectPoolConfigScriptableObject heartPoolConfig;

        public IObjectPool<GameObject> batteryObjectPool { get; private set; }
        [SerializeField] private ObjectPoolConfigScriptableObject batteryPoolConfig;

        public IObjectPool<GameObject> eggObjectPool { get; private set; }
        [SerializeField] private ObjectPoolConfigScriptableObject eggPoolConfig;

        public IObjectPool<GameObject> obstacleObjectPool { get; private set; }
        [SerializeField] private ObjectPoolConfigScriptableObject obstaclePoolConfig;

        public IObjectPool<GameObject> healthObjectPool { get; private set; }
        [SerializeField] private ObjectPoolConfigScriptableObject healthPoolConfig;
        
        

        private void Awake()
        {
            heartObjectPool = new ObjectPool<GameObject>(() => Instantiate(heartPoolConfig.prefab),
                OnTakeFromPoolDefault, OnReturnedToPoolDefault,
                OnDestroyPoolObjectDefault, false, heartPoolConfig.defaultCapacity,
                heartPoolConfig.maxPoolSize);

            batteryObjectPool = new ObjectPool<GameObject>(() => Instantiate(batteryPoolConfig.prefab),
                OnTakeFromPoolDefault, OnReturnedToPoolDefault,
                OnDestroyPoolObjectDefault, false, batteryPoolConfig.defaultCapacity,
                batteryPoolConfig.maxPoolSize);
            eggObjectPool = new ObjectPool<GameObject>(() => Instantiate(eggPoolConfig.prefab),
                OnTakeFromPoolDefault, OnReturnedToPoolDefault,
                OnDestroyPoolObjectDefault, false, eggPoolConfig.defaultCapacity,
                eggPoolConfig.maxPoolSize);
            obstacleObjectPool = new ObjectPool<GameObject>(() => Instantiate(obstaclePoolConfig.prefab),
                OnTakeFromPoolDefault, OnReturnedToPoolDefault,
                OnDestroyPoolObjectDefault, false, obstaclePoolConfig.defaultCapacity,
                obstaclePoolConfig.maxPoolSize);
            
            healthObjectPool = new ObjectPool<GameObject>(() => Instantiate(healthPoolConfig.prefab),
                OnTakeFromPoolDefault, OnReturnedToPoolDefault,
                OnDestroyPoolObjectDefault, false, healthPoolConfig.defaultCapacity,
                healthPoolConfig.maxPoolSize);
        }


        private void OnReturnedToPoolDefault(GameObject obj)
        {
            obj.SetActive(false);
        }

        private void OnTakeFromPoolDefault(GameObject obj)
        {
            obj.SetActive(true);
        }

        private void OnDestroyPoolObjectDefault(GameObject obj)
        {
            Destroy(obj.gameObject);
        }
    }
}